package com.example.myprojectoffeixue;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.google.android.gms.common.api.GoogleApiClient;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.localization.Gateway;
import com.localization.GlobalValue;
import com.localization.SendUtil;
import com.localization.SocketUdpClient;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends FragmentActivity implements ViewPager.OnPageChangeListener, TextToSpeech.OnInitListener {
    //------------------------
    String mresult;
    public static final String PRIVATE_SETTING = "com.iflytek.setting";           //缓存数据的名称
    private static final String TAG = "BasicIatActivity";
    // 语音听写对象
    private SpeechRecognizer mIat;
    // 语音听写UI
    private RecognizerDialog mIatDialog;
    // 用HashMap存储听写结果
    private HashMap<String, String> mIatResults = new LinkedHashMap<String, String>();
    private SharedPreferences mSharedPreferences;
    private Toast mToast;
    // 引擎类型0
    private String mEngineType = SpeechConstant.TYPE_CLOUD;
    int ret = 0; // 函数调用返回值
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;
    //--------------------------
    ArrayList<Fragment> datas = new ArrayList<Fragment>();
    private LinearLayout ll;
    private int count;
    private ViewPager vp;
    String mac;
    String t;
    public Kaiguanfg k2;
    public MyApplication m;
    String j;
    private FragmentTransaction transaction;
    public ChangJingfg f;
    public SheZhifg t1;
    public Housefg h1;
    private FragmentManager fm;
    private ImageView iv0;
    private ImageView iv1;
    private ImageView iv2;
   // private ImageView iv5;
    public Fragment currentfragment;
    private TextView tv;
    private TextView tv3;
    private TextView tv4;
   // private TextView tv5;
    private String speechTxt="语音命令错误"; // 需要朗读的内容
    private TextToSpeech textToSpeech;
    // ---------------界面的主入口-----------------------------
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        m = (MyApplication) getApplication();
        setContentView(R.layout.activity_main);
        initView();
        textToSpeech = new TextToSpeech(this, this);
        SpeechUtility.createUtility(this, SpeechConstant.APPID + "=5763509a");
        Log.d(TAG, "onCreate--->");
        initIat();
        //初始化组件 后期修改为，程序一进入的时候进行初始化
        mToast = Toast.makeText(getBaseContext(),"",Toast.LENGTH_SHORT);
    }
    @Override
    protected void onStart() {
        Log.d("hh","hehe");
        MyApplication.flag8=0;
        super.onStart();
    }
    //为主界面添加四个fragment，因为要获取网关下设备的个数，所以放在连接之后
    private void initView() {
        iv0 = (ImageView) findViewById(R.id.iv0_mian);
        iv1 = (ImageView) findViewById(R.id.iv1_main);
        iv2 = (ImageView) findViewById(R.id.iv2_main);
      //  iv5=(ImageView) findViewById(R.id.iv5_main);
        tv = (TextView) findViewById(R.id.textView1);
        tv3 = (TextView) findViewById(R.id.textView3);
        tv4 = (TextView) findViewById(R.id.textView4);
       // tv5 = (TextView) findViewById(R.id.textView5);
        k2 = new Kaiguanfg();
        f = new ChangJingfg();
        t1 = new SheZhifg();
        h1=new Housefg();
        datas.add(k2);
       // datas.add(h1);
        datas.add(f);
        datas.add(t1);
        vp = (ViewPager) findViewById(R.id.vp);
        vp.setOffscreenPageLimit(4);
        vp.setOnPageChangeListener(this);
        vp.setAdapter(new A(getSupportFragmentManager()));
        ll = (LinearLayout) findViewById(R.id.hsv_title);
        count = ll.getChildCount();
        for (int i = 0; i < count; i++) {
            final LinearLayout view = (LinearLayout) ll.getChildAt(i);
            view.setTag(i);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    int x = (Integer) view.getTag();
                    vp.setCurrentItem(x);
                    change(x);
                }
            });
        }
        vp.setCurrentItem(0);
    }

    protected void change(int x) {
       if(x==0){
           iv0.setImageResource(R.drawable.sb);
           iv1.setImageResource(R.drawable.cj);
           iv2.setImageResource(R.drawable.sz2);
          // iv5.setImageResource(R.drawable.cj);
           tv.setTextColor(Color.parseColor("#76a6ef"));
           tv3.setTextColor(Color.parseColor("#898989"));
           tv4.setTextColor(Color.parseColor("#898989"));
          // tv5.setTextColor(Color.parseColor("#898989"));
       }
       else if(x==2){
           iv0.setImageResource(R.drawable.sb2);
           iv1.setImageResource(R.drawable.cj);
           iv2.setImageResource(R.drawable.sz);
           //iv5.setImageResource(R.drawable.cj);
           tv.setTextColor(Color.parseColor("#898989"));
           tv4.setTextColor(Color.parseColor("#76a6ef"));
           tv3.setTextColor(Color.parseColor("#898989"));
          // tv5.setTextColor(Color.parseColor("#898989"));
       }
      /* else if(x==2){
           iv0.setImageResource(R.drawable.sb2);
           iv1.setImageResource(R.drawable.cj);
           iv2.setImageResource(R.drawable.sz);
          // iv5.setImageResource(R.drawable.cj);
           tv.setTextColor(Color.parseColor("#898989"));
           tv3.setTextColor(Color.parseColor("#898989"));
           tv4.setTextColor(Color.parseColor("#76a6ef"));
         //  tv5.setTextColor(Color.parseColor("#898989"));
       }*/else if(x==1){

           iv0.setImageResource(R.drawable.sb2);
           //iv5.setImageResource(R.drawable.cj2);
           iv1.setImageResource(R.drawable.cj2);
           iv2.setImageResource(R.drawable.sz2);

           tv.setTextColor(Color.parseColor("#898989"));
           tv3.setTextColor(Color.parseColor("#76a6ef"));
           tv4.setTextColor(Color.parseColor("#898989"));
           //tv5.setTextColor(Color.parseColor("#76a6ef"));
       }
    }
    class A extends FragmentStatePagerAdapter {
        public A(FragmentManager fm) {
            super(fm);
        }
        @Override
        public android.support.v4.app.Fragment getItem(int arg0) {
            // TODO Auto-generated method stub
            return datas.get(arg0);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return datas.size();
        }

    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
        // TODO Auto-generated method stub
    }
    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPageSelected(int arg0) {
        change(arg0);
    }


    // 为主界面添加四个fragment，因为要获取网关下设备的个数，所以放在连接之后
  /*  private void initView() {
        flag = true;
        m.main_flag = true;
        iv0 = (ImageView) findViewById(R.id.iv0_mian);
        iv1 = (ImageView) findViewById(R.id.iv1_main);
        iv2 = (ImageView) findViewById(R.id.iv2_main);
        tv = (TextView) findViewById(R.id.textView1);
        tv3 = (TextView) findViewById(R.id.textView3);
        tv4 = (TextView) findViewById(R.id.textView4);
        LinearLayout sb = (LinearLayout) findViewById(R.id.sb_textview);
        LinearLayout cj = (LinearLayout) findViewById(R.id.cj_textview);
        LinearLayout shezhi = (LinearLayout) findViewById(R.id.shezhi_textview);

        k2 = new Kaiguanfg();
        f = new ChangJingfg();
        t1 = new SheZhifg();

        fm = getSupportFragmentManager();
        transaction=null;
        transaction = fm.beginTransaction();
        transaction.add(R.id.vp, k2);
        transaction.commit();
        currentfragment = k2;
        sb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //ToastUtils.showToast(MainActivity.this,"设备");
                iv0.setImageResource(R.drawable.sb);
                iv1.setImageResource(R.drawable.cj);
                iv2.setImageResource(R.drawable.sz2);
                tv.setTextColor(Color.parseColor("#76a6ef"));
                tv3.setTextColor(Color.parseColor("#898989"));
                tv4.setTextColor(Color.parseColor("#898989"));
                if (!k2.isAdded()) {
                    transaction=null;
                    transaction = fm.beginTransaction();
                    transaction.hide(currentfragment).add(R.id.vp,k2).commit();
                } else {

                    if (currentfragment != k2 ) {
                        transaction=null;
                        transaction = fm.beginTransaction();
                        transaction.hide(currentfragment).show(k2).commit();
                    }else{
                        return;
                    }

                    if (m.flag4 == 1) {
                        k2.mainInterfaceImageIDs = new int[10];
                        k2.mainInterfaceStr = new String[10];
                        k2.lstItems.clear();
                        if (m.lsb.size() != 0) {
                            k2.mainInterfaceImageIDs[0] = R.drawable.kai;
                            k2.mainInterfaceStr[0] = "开关";
                        }
                        if (m.lsb1.size() != 0) {
                            k2.mainInterfaceImageIDs[1] = R.drawable.ms;
                            k2.mainInterfaceStr[1] = "门锁";
                        }
                        if (m.lsb2.size() != 0) {
                            k2.mainInterfaceImageIDs[2] = R.drawable.hw2;
                            k2.mainInterfaceStr[2] = "红外人体感应";
                        }
                        if (m.lsb3.size() != 0) {
                            k2.mainInterfaceImageIDs[3] = R.drawable.cl2;
                            k2.mainInterfaceStr[3] = "窗帘";
                        }
                        if (m.lsb4.size() != 0) {
                            k2.mainInterfaceImageIDs[4] = R.drawable.mc;
                            k2.mainInterfaceStr[4] = "门磁";
                        }
                        if (m.lsb5.size() != 0) {
                            k2.mainInterfaceImageIDs[5] = R.drawable.qudiana;
                            k2.mainInterfaceStr[5] = "取电开关";

                        }
                        if (m.lsb6.size() != 0) {
                            k2.mainInterfaceImageIDs[6] = R.drawable.hwzfq;
                            k2.mainInterfaceStr[6] = "红外转发器";
                        }
                        if (m.lsb7.size() != 0) {
                            k2.mainInterfaceImageIDs[7] = R.drawable.zykt;
                            k2.mainInterfaceStr[7] = "中央空调";
                        }
                        if (m.lsb8.size() != 0) {
                            k2.mainInterfaceImageIDs[8] = R.drawable.chazuokai;
                            k2.mainInterfaceStr[8] = "智能插座";
                        }

                        for (int j = 0; j < k2.mainInterfaceImageIDs.length; j++) {
                            if (k2.mainInterfaceImageIDs[j] != 0) {
                                HashMap<String, Object> map = new HashMap<String, Object>();
                                map.put("itemsImage", k2.mainInterfaceImageIDs[j]);
                                map.put("itemsText", k2.mainInterfaceStr[j]);
                                k2.lstItems.add(map);
                            }
                        }
                        if (k2.imageItems != null) {
                            k2.imageItems.notifyDataSetChanged();
                            m.flag4 = 0;
                        }

                    }
                }
                currentfragment = k2;
            }
            // 使用当前Fragment的布局替代id_content的控件

        });

        cj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               // ToastUtils.showToast(MainActivity.this,"场景");

                iv0.setImageResource(R.drawable.sb2);
                iv1.setImageResource(R.drawable.cj2);
                iv2.setImageResource(R.drawable.sz2);
                tv.setTextColor(Color.parseColor("#898989"));
                tv3.setTextColor(Color.parseColor("#76a6ef"));
                tv4.setTextColor(Color.parseColor("#898989"));

                if (!f.isAdded()) {
                    transaction=null;
                    transaction = fm.beginTransaction();
                    transaction.hide(currentfragment).add(R.id.vp,f).commit();
                } else {
                    if (currentfragment!= f) {
                        transaction=null;
                        transaction = fm.beginTransaction();
                        transaction.hide(currentfragment).show(f).commit();

                    }else{
                        Log.d("44","ii");
                        return;
                    }
                    // 使用当前Fragment的布局替代id_content的控件
                }
                currentfragment = f;

            }
        });



        shezhi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               // ToastUtils.showToast(MainActivity.this,"设置");

                iv0.setImageResource(R.drawable.sb2);
                iv1.setImageResource(R.drawable.cj);
                iv2.setImageResource(R.drawable.sz);
                tv.setTextColor(Color.parseColor("#898989"));
                tv3.setTextColor(Color.parseColor("#898989"));
                tv4.setTextColor(Color.parseColor("#76a6ef"));
               if (!t1.isAdded()) {
                   transaction=null;
                   transaction = fm.beginTransaction();
                   transaction.hide(currentfragment).add(R.id.vp,t1).commit();
                } else {
                    if (currentfragment != t1) {
                        transaction=null;
                        transaction = fm.beginTransaction();
                        transaction.hide(currentfragment).show(t1).commit();
                    }else{
                        return;
                    }
                }
                currentfragment = t1;
                // 使用当前Fragment的布局替代id_content的控件
            }

        });

    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //    super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        //    super.onRestoreInstanceState(savedInstanceState);
    }*/

    @Override
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS) {
            int result = textToSpeech.setLanguage(Locale.US);
            if (result == TextToSpeech.LANG_MISSING_DATA
                    || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                Toast.makeText(this, "数据丢失或不支持", Toast.LENGTH_SHORT).show();
            }
        }
    }
    @Override
    protected void onStop() {
        super.onStop();
        textToSpeech.stop(); // 不管是否正在朗读TTS都被打断
        textToSpeech.shutdown(); // 关闭，释放资源
    }
    public void showTip(String content){
        mToast.setText(content);
        mToast.show();
    }

    private void initIat() {
        // 使用SpeechRecognizer对象，可根据回调消息自定义界面；
        mIat = SpeechRecognizer.createRecognizer(this, mInitListener);
        // 初始化听写Dialog，如果只使用有UI听写功能，无需创建SpeechRecognizer
        // 使用UI听写功能，请根据sdk文件目录下的notice.txt,放置布局文件和图片资源
        mIatDialog = new RecognizerDialog(this, mInitListener);
        mSharedPreferences = getSharedPreferences(PRIVATE_SETTING, Activity.MODE_PRIVATE);

    }

    /**
     * 初始化监听器
     */
    private InitListener mInitListener = new InitListener() {
        @Override
        public void onInit(int code) {
            Log.d(TAG, "SpeechRecognizer init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                showTip("初始化失败，错误码：" + code);
            }
        }
    };

    /**
     * 听写UI监听器
     */
    private RecognizerDialogListener mRecognizerDialogListener = new RecognizerDialogListener() {
        public void onResult(RecognizerResult results, boolean isLast) {
            int flag=0;
            mresult= printResult(results);
            String name_device=mresult.substring(2);
            String cmd=mresult.substring(0,2);
            ArrayList<SheBeiClass> all_device=new ArrayList<SheBeiClass>();
            all_device.addAll(m.lsb);
            all_device.addAll(m.lsb1);
            all_device.addAll(m.lsb3);
            for(int i=0;i<all_device.size();i++){
                if(name_device.equals(all_device.get(i).deviceName)){
                    Kuaiguanutil k = new Kuaiguanutil();

                    if("0100".equals(all_device.get(i).deviceId)){
                        k.cmd = "1007";
                    }else if("010B".equals(all_device.get(i).deviceId) || "010A".equals(all_device.get(i).deviceId)){
                        k.cmd="1005";
                    }else if("0002".equals(all_device.get(i).deviceId)){
                        k.cmd="1008";
                    }
                    if("打开".equals(cmd)){
                        k.status="01";
                    }else if("关闭".equals(cmd)){
                        k.status="00";
                    }
                    k.ieee = all_device.get(i).ieee;
                    k.port = all_device.get(i).port;
                    k.mac = all_device.get(i).mac;
                    String j = JSON.toJSONString(k);
                    Log.d("cmd", j);
                    //wsc.sendTextMessage(j);
                    if (m.flag3) {
                        flag=1;
                        m.c.send(j);}
                }

            }
    if(flag==0){
        if (textToSpeech != null && !textToSpeech.isSpeaking()) {
            textToSpeech.setPitch(0.5f);// 设置音调，值越大声音越尖（女生），值越小则变成男声,1.0是常规
            textToSpeech.speak(speechTxt,TextToSpeech.QUEUE_FLUSH, null);
        }
   }
        }

        /**
         * 识别回调错误.
         *
         *
         *
         *
         */
        public void onError(SpeechError error) {
            showTip(error.getPlainDescription(true));
        }
    };
    /**
     * 参数设置
     *
     * @param
     * @return
     */
    public void setParam() {
        // 清空参数
        mIat.setParameter(SpeechConstant.PARAMS, null);
        // 设置听写引擎
        mIat.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
        // 设置返回结果格式
        mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");
        String lag = mSharedPreferences.getString("iat_language_preference", "mandarin");
        if (lag.equals("en_us")) {
            // 设置语言
            mIat.setParameter(SpeechConstant.LANGUAGE, "en_us");
        } else {
            // 设置语言
            mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
            // 设置语言区域
            mIat.setParameter(SpeechConstant.ACCENT, lag);
        }
        // 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
        mIat.setParameter(SpeechConstant.VAD_BOS, mSharedPreferences.getString("iat_vadbos_preference", "4000"));
        // 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
        mIat.setParameter(SpeechConstant.VAD_EOS, mSharedPreferences.getString("iat_vadeos_preference", "1000"));
        // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mIat.setParameter(SpeechConstant.ASR_PTT, mSharedPreferences.getString("iat_punc_preference", "1"));
        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mIat.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/iat.wav");
    }


    /**
     * 触发点击事件时的方法
     */
    public void clickMethod() {
        mIatResults.clear();
        setParam();
        mIatDialog.setListener(mRecognizerDialogListener);
        mIatDialog.show();
        showTip(getString(R.string.text_begin));

    }

    /**
     * 显示结果,并赋值到EditText文本框中
     *
     * @param results
     * @parameditText
     */
    private String printResult(RecognizerResult results) {
        String text = JsonParser.parseIatResult(results.getResultString());
        String sn = null;
        // 读取json结果中的sn字段
        try {
            JSONObject resultJson = new JSONObject(results.getResultString());
            sn = resultJson.optString("sn");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        mIatResults.put(sn, text);

        StringBuffer resultBuffer = new StringBuffer();
        for (String key : mIatResults.keySet()) {
            resultBuffer.append(mIatResults.get(key));
        }
        String content = resultBuffer.toString();
        content = content.replace("。", "".trim());           //去掉最后面的 。
        return content;
    }
    @Override
    protected void onDestroy() {
               Log.d("毁灭了","主界面销毁了");
        if( m.c!=null){
               MyApplication.flag8=1;
               m.c.close();
               m.flag6 = true;
               m.flag7=true;
        }

           if(m.udp!=null){
               m.udp.close();
         }
            Log.d("关闭本地连接","关闭本地连接");
        if(GlobalValue.mGateway!=null) {
            for (int i = 0; i < GlobalValue.mGateway.msocket.size(); i++) {
                GlobalValue.mGateway.close();
            }
                GlobalValue.mGateway.objectlist.clear();
                GlobalValue.mGateway.msocket.clear();
                GlobalValue.mGateway.MacSocke.clear();

        }
            super.onDestroy();}


//判断是否为内网操作









}
